package top.lcm889.juc.线程安全问题.model;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Coder-lcm
 * @date 2021/4/10
 */
public class Account2 {
    private String No;
    private Double balance;
    // 是否有人存钱的标志
    private boolean flag = false;

    public Account2() {
    }

    public Account2(String no, Double balance) {
        No = no;
        this.balance = balance;
    }

    public String getNo() {
        return No;
    }

    public void setNo(String no) {
        No = no;
    }

    public Double getBalance() {
        return balance;
    }

    public void setBalance(Double balance) {
        this.balance = balance;
    }

    @Override
    public int hashCode() {
        return No.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj instanceof Account2) {
            Account2 account = (Account2) obj;
            return account.No.equals(No);
        }
        return false;
    }

    /**
     * 模拟存钱的操作
     * @param money
     * @throws InterruptedException
     */
    public synchronized void plusMoney(double money) throws InterruptedException {
        if (flag) {
            //如果已经有人存钱了，就先阻塞进程，暂时不存
            System.out.println(Thread.currentThread().getName() + "：存钱阻塞");
            wait();
        }else {
            // 执行存钱操作
            System.out.println(Thread.currentThread().getName() + ": 存钱 " + money);
            balance += money;
            System.out.println(Thread.currentThread().getName()  + ": 余额 " + balance);
            flag = true;
            // 唤醒所有等待的进程
            notifyAll();
        }
    }

    /**
     * 模拟取钱的操作
     * @param money
     * @throws InterruptedException
     */
    public synchronized void reduceMoney(double money) throws InterruptedException {
        if (!flag) {
            //如果还没有人存钱，就先不取
            System.out.println(Thread.currentThread().getName() + "：取钱阻塞");
            wait();
        }else {
            // 执行取钱操作
            System.out.println(Thread.currentThread().getName() + ": 取钱 " + money);
            balance -= money;
            System.out.println(Thread.currentThread().getName()  + ": 余额 " + balance);
            flag = false;
            // 唤醒所有等待的进程
            notifyAll();
        }
    }
}
